﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace Gmantis.Controls
{
    [TemplatePart(Name = "Button", Type = typeof(Button))]
    public class SplitButton : DropDown
    {
        // Fields
        internal Button _elementButton;
        internal bool _isLoaded;
        internal const string ButtonElementName = "Button";

        // Events
        public event RoutedEventHandler Click;

        // Methods
        public SplitButton()
        {
            base.DefaultStyleKey = typeof(SplitButton);
        }

        private T GetTemplateChild<T>(string childName, bool required, ref string errors) where T : class
        {
            DependencyObject templateChild = base.GetTemplateChild(childName);
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "template part", childName, templateChild, required, ref errors);
            return (templateChild as T);
        }

        private static Storyboard GetTemplateChildResource(FrameworkElement root, string resourceName, bool required, ref string errors)
        {
            return GetTemplateChildResource<Storyboard>(root, resourceName, required, ref errors);
        }

        private static T GetTemplateChildResource<T>(FrameworkElement root, string resourceName, bool required, ref string errors) where T : class
        {
            object child = root.Resources[resourceName];
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "resource", resourceName, child, required, ref errors);
            return (child as T);
        }

        private void InitializeButtonPart()
        {
            this._elementButton.Click += delegate(object s, RoutedEventArgs e)
            {
                if (this.Click != null)
                {
                    this.Click(s, e);
                }
            };
        }

        public override void OnApplyTemplate()
        {
            string errors = string.Empty;
            base.OnApplyTemplate();
            this._isLoaded = true;
            this._elementButton = this.GetTemplateChild<Button>("Button", true, ref errors);
            if (this._elementButton != null)
            {
                this.InitializeButtonPart();
            }
            if (!string.IsNullOrEmpty(errors))
            {
                this._isLoaded = false;
                if ((base.Template != null) && !PlatformIndependent.IsInDesignMode(this))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Template cannot be applied to C1SplitButton.\nDetails: {0}", new object[] { errors }));
                }
            }
        }
    }
}
